import { useEffect, useState } from 'react'
import { history } from 'umi'
import { CertificateCard } from './components/CertificateCard'
import { fetchCertificates } from '../api'
import styles from './index.module.less'
import NavBar from '@/components/Global/NavBar'
import { YesNo } from '@/constant/enum'
import Empty from '@/components/Common/Empty'
import { DotLoading } from 'antd-mobile'
import type { SearchForm, CertificateResult as ICertificateResult } from '../interface'

const CertificateResult = () => {
    const searchParams = (history.location.query as unknown) as SearchForm & { from?: string }

    const [loading, setLoading] = useState<boolean>(false)

    const [certificate, setCertificate] = useState<ICertificateResult>()

    const isEmpty = !loading && (certificate?.list || []).length === 0

    const onBack = () => history.push('/login')

    useEffect(() => {
        const initCertificates = async () => {
            try {
                setLoading(true)
                const { data } = await fetchCertificates({
                    ...searchParams,
                    is_mobile: YesNo.Yes,
                })
                setCertificate(data)
            } finally {
                setLoading(false)
            }
        }

        initCertificates()
    }, [searchParams])

    return (
        <div className={styles.page}>
            <header>
                <NavBar title="证书查询结果" onBack={onBack} />
                <div>
                    <span>姓名</span>
                    <span>{searchParams?.realname || '-'}</span>
                </div>
                <div>
                    <span>身份证号</span>
                    <span>{searchParams?.idcard || '-'}</span>
                </div>
            </header>

            {loading && (
                <div style={{ width: '100%', margin: '20px 0', textAlign: 'center' }}>
                    <DotLoading />
                </div>
            )}

            {isEmpty && <Empty type="noResult" description="暂时没有符合条件的结果" />}

            {!isEmpty && (
                <section>
                    {certificate?.list.map(item => (
                        <CertificateCard key={item.serial_number} {...item} />
                    ))}
                </section>
            )}
        </div>
    )
}

export default CertificateResult
